<template>
    <el-upload
        v-model:file-list="fileList"
        action="#"
        :auto-upload="false" 
        :limit="props.limit || 1"
        :list-type="props.listType || 'picture-card'"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-exceed="fileExceed"
        :on-change="handleChange"
    >
        <el-icon><Plus /></el-icon>
    </el-upload>
    <ElDialog v-model="dialogImg" width="800px">
        <el-image style="width: 100%" :src="dialogImageUrl" fit="cover" />
    </ElDialog>

</template>
<script setup>
import { ElUpload, ElIcon, ElMessage, ElDialog, ElImage } from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import { ref, computed } from 'vue';
const props = defineProps(['limit', 'listType', 'fileType', 'fileSize', 'modelValue'])
const emit = defineEmits(['update:modelValue'])
const fileList = computed({
    set:(val) =>{
        emit('update:modelValue', val)
    },
    get:() => {
        return props.modelValue || []
    }
})
const dialogImageUrl = ref()
const dialogImg = ref(false)
// 删除附件
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
// 查看图片
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogImg.value = true
}
// 超出文件个数限制提示
const fileExceed = () => {
    ElMessage.error('只能上传一个文件！')
}
// 图片发上变化
const handleChange = (res) => {
    let check = beforeAvatarUpload(res.raw)
    if(!check) fileList.value = []
}
// 文件检测
const beforeAvatarUpload = (rawFile) => {
    console.log("rawFile", rawFile);
    if (props.fileType&&!props.fileType.includes(rawFile.type.split('/').pop())) {
        ElMessage.error('请上传'+props.fileType+'格式的图片')
        return false
    }
    if (props.props && (rawFile.size / 1024 / 1024 > props.props)) {
        ElMessage.error('文件不能大于'+props.props+'MB!')
        return false
    }
    return true
}
</script>